import inquirer from "inquirer";
import { NodeSSH } from "node-ssh";
import path from "path";
import fs from "fs";
import { pageUrl } from "../src/config/index.js"
import { exec, execSync } from "child_process";

(async function () {
  const arg = process.argv[2];
  let command;
  let projectName;

  if (arg) {
    if (pageUrl[arg]) {
      projectName = arg;
      command = `set VITE_PAGE=${arg} && tsc && vite build`;
    } else {
      return console.error("不合法参数")
    }
  } else {
    const choices = Object.keys(pageUrl);
    const { project } = await inquirer.prompt([{ type: 'rawlist', name: 'project', message: '选择你要打包的项目：', choices }])
    projectName = project;
    command = `set VITE_PAGE=${project} && tsc && vite build`;
  }
  exec(command).stdout.on("data", (data) => {
    console.log(`stdout: ${data}`);
  }).on("error", (err) => {
    return console.error(err);
  }).on("end", async () => {
    let config;
    try {
      const res = fs.readFileSync(path.resolve(pageUrl[projectName], "../server.config.json"))
      config = JSON.parse(res);

    } catch (error) {
      const { release } = await inquirer.prompt({ name: "release", type: "confirm", message: "是否开启自动部署？", default: true })
      console.log("服务器自动部署设置：");
      if (release) {
        const { host } = await inquirer.prompt({ name: "host", message: "host：", type: "input" })
        const { port } = await inquirer.prompt({ name: "port", message: "port：", type: "input", default: 22 })
        const { username } = await inquirer.prompt({ name: "username", message: "username：", type: "input", default: "root" })
        const { password } = await inquirer.prompt({ name: "password", message: "password：", type: "input" })
        const { remoteDir } = await inquirer.prompt({ name: "remoteDir", message: "remoteDir：", type: "input" })
        const { timestamp } = await inquirer.prompt({ name: "timestamp", type: "confirm", message: "open package timestamp？", default: false })

        config = {
          open: true, // 是否自动部署
          host, // 服务器host
          port, // 服务器端口号
          username, // 服务器用户名
          password, // 服务器密码
          remoteDir, // 服务器上传路径
          timestamp // 包是否自动添加时间戳
        }
        fs.writeFileSync(path.resolve(pageUrl[projectName], "../server.config.json"), JSON.stringify(config, null, 2)) //缩进2个字符

      }
    }
    if (config.open) {
      console.log("正在发布...");
      // 连接并发布
      await releaseServer({ localSrc: path.resolve(`dist/${projectName}.zip`), projectName, ...config })
    }
    const { submit } = await inquirer.prompt({ name: "submit", type: "confirm", message: "是否需要提交git？", default: true })
    if (submit) {
      const store = execSync("git config --get credential.helper")
      if (store.toString() != "store") {
        execSync("git config credential.helper store")
      }

      const { commit } = await inquirer.prompt({ name: "commit", type: "input", message: "请输入提交信息" })
      exec(`git add . && git commit -m "${commit}" && git push`).stdout.on("data", (data) => {
        console.log(`stdout: ${data}`);
      }).on("error", (err) => {
        return console.error(err);
      }).on("end", () => {
        console.log("提交成功");
      })
    }
  })
})()

async function releaseServer(config) {
  const filename = config.timestamp ? `${projectName}_${new Date().getTime()}.zip` : path.basename(config.localSrc);
  const remoteSrc = `${config.remoteDir}/${filename}`;
  const ssh = new NodeSSH()
  try {
    console.log("等待SSH连接...");
    await ssh.connect({
      host: config.host,
      port: config.port,
      username: config.username,
      privateKey: fs.readFileSync('C:\\Users\\Administrator\\.ssh\\id_rsa').toString()
    });
    console.log("等待文件上传...");
    await ssh.putFile(config.localSrc, remoteSrc);
    console.log("文件上传成功:", remoteSrc);

    await ssh.execCommand(`cd ${config.remoteDir}; unzip -o ${path.basename(config.localSrc)}`);
    console.log("文件解压完毕");
    console.log("配置信息查看：", path.resolve(pageUrl[config.projectName], "../server.config.json"));

  } catch (error) {
    console.log(error);
  } finally {
    ssh.dispose()
  }

}

